package cn.parus.dynamicRouter.controller;

import cn.parus.commons.common.Result;
import cn.parus.dynamicRouter.component.RefreshRouteLocator;
import cn.parus.dynamicRouter.dao.Repository.ApiRepository;
import cn.parus.dynamicRouter.entity.ApiInfo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: Axel
 * @Description: TODO 路由管理api
 **/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/route-api")
public class RouteMGController {

    @Autowired
    ApiRepository apiRepository;
    @Autowired
    RefreshRouteLocator refreshRouteLocator;

    /**
     * 获取所有的服务
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getRoutes")
    public Result getRoutes(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageInfo<ApiInfo> routes = apiRepository.getAll(pageNum, pageSize);
            return Result.success(routes);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新/新增服务
     * @param apiInfo
     * @return
     */
    @PutMapping("/updateRoutes")
    public Result updateRoutes(@RequestBody ApiInfo apiInfo) {
        try {
            apiRepository.save(apiInfo);
            // 全局刷新路由
            refreshRouteLocator.buildRoutes();
            return Result.success("更新成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除服务
     * @param id
     * @return
     */
    @DeleteMapping("/deleteRoutes/{id}")
    public Result deleteRoutes(@PathVariable String id) {
        try {
            apiRepository.delete(id);
            // 全局刷新路由
            refreshRouteLocator.buildRoutes();
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 刷新路由
     * @return
     */
    @GetMapping("/freshRoute")
    public Result freshRoute() {
        try{
            refreshRouteLocator.buildRoutes();
            return Result.success("刷新成功");
        } catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据策略名查询服务
     * @return
     */
    @GetMapping("/selectByServiceId")
    public Result selectByServiceId(@RequestParam String serviceId) {
        try{
            List<ApiInfo> list = apiRepository.getServiceById(serviceId);
            return Result.success(list);
        } catch (Exception e){
            return Result.error(e.getMessage());
        }
    }
}
